<template>
  <div class="generate-image-wrapper">
    
    
    <!-- <span class="warn-tip"><Icon type="ios-alert-outline" />最多可创建三个镜像</span> -->
    <div class="flex-between wp100">
      <Form
        ref="form"
        :model="formData"
        :rules="rules"
        :label-width="96"
        inline
        style="width: 88%"
      >

        <div class="flex showlabel" style="flex: auto">
          <FormItem
              style="width: 100%"
              label=""
              prop="deviceBaseType"
          >
            <div class="sw-label">关联实物设备:</div>
            <RadioGroup v-model="formData.bandingStatus" style="width: 108px;" @on-change="changeBind">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <i-select
                v-if="formData.bandingStatus===1"
                style="width: calc(100% - 230px)"
                clearable
                filterable
                multiple
                placeholder="请选择实物设备类型"
                v-model="formData.deviceBaseType"
            >
              <i-option :value="item.dictCode" v-for="(item,idx) in deviceTypes" :key="item.dictCode">{{item.dictCnCode}}</i-option>
            </i-select>
          </FormItem>
        </div>

<!--        <div class="flex showlabel" style="flex: auto">-->
<!--          <FormItem-->
<!--              style="width: 100%"-->
<!--              v-if="formData.bandingStatus != 0"-->
<!--              label="镜像配置项"-->
<!--              prop="deviceBaseType"-->
<!--          >-->
<!--          </FormItem>-->
<!--        </div>-->
        
        
        <div class="flex" style="flex: auto">
          <FormItem
            label=" "
            prop="imageRef"
            style="width: 40%"
            :show-message="false"
          >
            <Select filterable
              v-model="formData.imageRef"
              placeholder="镜像"
              @on-change="changeImage"
              filterable clearable
            >
              <Option
                v-for="(value, key) in imageList"
                :value="value.id"
                :key="key"
                :title="value.imageName"
                >{{ value.imageName }}</Option
              >
            </Select>
          </FormItem>
          <FormItem
            label=" "
            prop="flavorRef"
            :show-message="false"
            style="width: 40%"
          >
            <Select filterable
              v-model="formData.flavorRef"
              placeholder="配额"
              @on-change="changeFlavor"
              filterable
            >
              <Option
                v-for="(value, key) in flavorList"
                :value="value.id"
                :key="key"
                :title="value.flavorName"
                >{{ value.flavorName }}</Option
              >
            </Select>
          </FormItem>
          <FormItem
            label=" "
            prop="count"
            :show-message="false"
            style="width: 19%"
          >
            <Select filterable v-model="formData.count" placeholder="数量">
              <Option :value="num" :key="num" v-for="num in maxsize">{{num}}</Option>
            </Select>
          </FormItem>

          <div style="min-width: 100px;">
<!--       镜像不限制数量     :disabled="count >= 3"-->
            <Button
                type="primary"
                class="no-radius"
                @click="addImage()"
              
            >创建</Button
            >
            <WarningTip content="最多可创建三个镜像"></WarningTip>
          </div>
        </div>
      </Form>

    </div>
    <div class="image-wrapper" v-if="selectImageList.length > 0">
      <div class="image-item header flex-between">
        <span class="text-ellipsis">镜像名称</span>
        <span class="text-ellipsis">配额</span>
        <span class="text-ellipsis">虚拟机个数</span>
        <span class="text-ellipsis">操作</span>
      </div>
      <div
        v-for="(image, index) in selectImageList"
        :key="`${index}${image.imageRef}`"
        class="image-item flex-between"
      >
        <span class="text-ellipsis" :title="image.imageName">{{
          image.imageName
        }}</span>
        <span class="text-ellipsis" :title="image.flavorName">{{
          image.flavorName
        }}</span>
        
        <span class="text-ellipsis">{{ image.count }}</span>
<!--        <span class="text-ellipsis">{{ getTypename(image.deviceBaseType) }}</span>-->
        <span
          class="text-ellipsis"
          @click="delImage(index)"
          style="color: #db4747; cursor: pointer"
          >删除</span
        >
      </div>
    </div>
    <Button
      long
      type="primary"
      @click="templateAutomatic"
      v-if="selectImageList.length > 0"
      >生成模板</Button
    >
  </div>
</template>
<script>
import {getDeviceType} from '@/api/selfStudy/courseExp.js';
import { getallImage, getallFlavor } from '@/api/question';
import { getTempInfpByID } from '@/api/proTemplate.js';
import { templateAutomatic,templateAutomaticImage } from '@/api/selfStudy/courseExp';
export default {
    name: 'GenerateTemplate',
    props:['devicetype'],
    data() {
        return {
            maxsize:30,
            deviceTypes:[],
            deviceBaseType:this.devicetype,
            formData: { deviceBaseType:this.devicetype,bandingStatus:this.devicetype?1:0,imageRef: '', flavorRef: '', count: 1 },
            rules: {
                imageRef: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'blur,change'
                    }
                ],
                flavorRef: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'blur,change'
                    }
                ],
                count: [
                    {
                        type: 'number',
                        required: true,
                        min: 1,
                        max: this.maxsize,
                        trigger: 'blur,change'
                    }
                ]
            },
            imageList: [],
            flavorList: [],
            selectImageList: [],
            current: {
                image: {},
                flavor: {}
            }
        };
    },
    computed: {
        count() {
            let count = this.selectImageList.reduce((pre, cur, index) => {
                return pre + cur.count;
            }, 0);
            return count;
        }
    },
    mounted() {
        this.getAllImage();
        this.getAllFlavor();
        this.getDeviceType()
    },
    methods: {
      changeBind(){
        if(this.formData.bandingStatus===0){
          this.formData.deviceBaseType=''
        }
        
      },
      getTypename(type){
        let name='-'
        this.deviceTypes.forEach((item) =>{// :key="item.dictCode">{{item.dictCnCode}}
          if(item.dictCode === type){
            name = item.dictCnCode
          } 
        })
        
        return name
      },
      getDeviceType(){
        getDeviceType().then(res => {
          if (res.code == 1 && res.data) {// dictCode: 'VC', dictCnCode:
            let dtype = res.data.items||[]

            this.deviceTypes = dtype
          } else {
            console.error('获取实物设备类型失败，请刷新重试')
          }
        }).catch(error => {
          this.$Message.error({
            content: error,
            duration: 3,
          })
        })
      },
        addImage() {
            this.$refs['form']
                .validate((valid) => {
                    if (valid) {
                        // if (this.count + this.formData.count > 3) {
                        //     this.$Message.warning('最多可创建三个镜像');
                        //     return;
                        // }
                        let imageName = this.current.image.imageName;
                        let flavorName = this.current.flavor.flavorName;
                        let item = Object.assign({}, this.formData, {
                            imageName,
                            flavorName
                        });
                        this.selectImageList.push(item);
                    } else {
                    }
                })
                .catch((error) => {});
        },
        delImage(index) {
            this.selectImageList.splice(index, 1);
        },
        addImageList() {},
        changeImage(id) {
            if (!id) {
                return;
            }
            this.current.image = this.imageList.find((item) => item.id === id);
            this.formData.flavorRef = '';
            this.flavorList = this.flavorListCopy.filter(
                (item) =>
                    item.ram > Number(this.current.image.minRam) &&
                    item.disk > Number(this.current.image.minDisk)
            );
          
        },
        changeFlavor(id) {
            this.current.flavor = this.flavorListCopy.find((item) => item.id === id);
        },
        templateAutomatic() {
            let vmList = []; // vmList
            this.deviceBaseType = this.formData.deviceBaseType
            // let physicalList = [{
            //       bandingStatus: this.formData.bandingStatus,
            //       deviceId: "",
            //       type: this.formData.deviceBaseType
            // }]
            let dbasetype = this.formData.deviceBaseType||[]
            let physicalList = dbasetype.map(item=>{
              return {
                bandingStatus: this.formData.bandingStatus,
                deviceId: "",
                type: item
              }
            })
          
          
          
            this.selectImageList.forEach((item) => {
                let { imageRef, flavorRef } = item;
                for (let i = 0; i < item.count; i++) {
                  vmList.push({
                    imageId:imageRef,
                    flavorId:flavorRef
                    });
                  // physicalList.push({
                  //     bandingStatus: item.bandingStatus,
                  //     deviceId: "",
                  //     type: item.deviceBaseType
                  //   });
                }
            });
            
            let data = {
              physicalList:physicalList,
              vmList:vmList
            }
            
            
          templateAutomaticImage(data).then(({ code, data, message }) => {
                if (code === 1) {
                    let templateId = data;
                    this.querytempByID(templateId);
                } else {
                    this.$Message.error(message);
                }
            });
        },
        querytempByID(id) {
            getTempInfpByID(id)
                .then((res) => {
                    if (res.data.code === 1) {
                        this.selectImageList = [];
                        // this.formData = { imageRef: '', flavorRef: '', count: 1 };
                        this.$refs['form'].resetFields();
                        this.$emit('on-success', {
                            id: id,
                            name: res.data.data.name,
                            deviceBaseType:this.deviceBaseType
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getAllImage() {
            let obj = {};
            let search = {
                pageIndex: 1,
                pageSize: 9999
            };
            getallImage(obj, search).then((data) => {
                if (data.code === 1) {
                    this.imageList = data.data.items;
                }
            });
        },
        getAllFlavor() {
            const search = {
                pageIndex: 1,
                pageSize: 9999
            };
            debugger
            getallFlavor(search).then((data) => {
                if (data.code === 1) {
                    let flavorList = data.data.items||[];

                  
                    // flavorList = flavorList.filter(
                    //     (item) => item.cpu <= 4 && item.disk <= 80 && item.ram <= 8192
                    // );
                    this.flavorList = flavorList;
                    this.flavorListCopy = flavorList;
                }
            });
        }
    }
};
</script>
<style scoped>
.w100 {
  width: 100px;
}
.wp100 {
  width: 100%;
}
.no-radius {
  border-radius: 0;
}
.generate-image-wrapper {
  padding: 4px 6px;
  /* background: #91979f; */
}
.generate-image-wrapper /deep/ .ivu-form .ivu-form-item-label {
  display: none;
}

.generate-image-wrapper  /deep/ .ivu-form .showlabel .ivu-form-item-label {
  display: block !important;
}
.showlabel{
  margin-bottom: 10px;
  width: 100%;
}
.showlabel /deep/ .ivu-form-item-content{
  display: flex;
}
.sw-label{
  margin-right: 12px;
}


.generate-image-wrapper /deep/ .ivu-form-item .ivu-form-item {
  margin-right: 0;
}
.ivu-form-item {
  margin-bottom: 0;
}
.image-wrapper {
  margin: 10px 0;
}
.image-item {
  display: flex;
}
.image-item > span {
  flex: 1;
  padding: 0 4px;
  text-align: center;
  /* border-bottom: 1px solid var(--table-border); */
  color: rgba(0, 0, 0, 0.4);
  /* border-bottom: var(--divider-color);
    color: var(--default-color); */
}
.image-item > span:not(:last-child) {
  margin-right: 2px;
}
.image-item.header > span {
  background: rgb(158, 186, 233);
  color: rgba(29, 28, 28, 0.8);
}
.warn-tip {
  color: #f90;
  word-break: break-all;
}
</style>

